package com.yyaccp.itrip.auth.controller;

import com.yyaccp.itrip.auth.exception.UserLoginFailedException;
import com.yyaccp.itrip.auth.service.LoginService;
import com.yyaccp.itrip.beans.domain.ItripUser;
import com.yyaccp.itrip.beans.dto.Dto;
import com.yyaccp.itrip.utils.DtoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 天天向上 （john.yi@qq.com）
 * @date 2020/11/13.
 */
@RestController
@RequestMapping("/api")
public class LoginController {
    @Autowired
    private LoginService loginService;

    @RequestMapping(value = "/dologin", method = RequestMethod.POST)
    public Dto login(String name, String password, HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        ItripUser user;
        try {
            user = loginService.login(name, password);
        } catch (UserLoginFailedException e) {
            return DtoUtil.returnFail(e.getMessage(),"30002");
        }
        return DtoUtil.returnSuccess("登录成功",loginService.createToken(user, userAgent));
    }
}
